package org.dei.perla.sys.core;

import java.io.File;
import java.io.StringReader;
import java.util.ArrayList;

import org.dei.perla.sys.device.plugnplay.plugnplaymanager.ClassTreeManager;
import org.dei.perla.sys.device.plugnplay.plugnplaymanager.Compiler;
import org.dei.perla.utils.pipe.Pipe;
import org.dei.perla.utils.waiter.Waitable;
import org.dei.perla.utils.waiter.Waiter;

import com.sun.org.apache.xalan.internal.xsltc.compiler.CompilerException;

public class FunctionalityProxyComponentFactory extends DefaultAgent<String, Object> {

	private Waiter<Pipe<String>> waiter;
	private String defaultPackage;
	private static String PROPERTY_NAME = "FPC_FACTORY_DEFAULT_GENERATED_CLASSES_PACKAGE"; 
	
	public FunctionalityProxyComponentFactory(String parName) {
		super(parName);
		PerlaRuntime runtime = PerlaRuntime.getDefaultRuntime();
		defaultPackage = runtime.getProperty(PROPERTY_NAME);
		if(defaultPackage == null)
			defaultPackage = "org.dei.perla.sys.device.plugnplay.xsdgeneratedclasses";
		
	}

	@Override
	public void setInputPipe(Pipe<String> pipe) {
		// TODO Auto-generated method stub
		super.setInputPipe(pipe);
		waiter = new Waiter<Pipe<String>>();
		waiter.addWaitable(this.pipeInput.getWaitable());
	}

	@Override
	public ArrayList<String[]> inspect() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void loop() throws Exception {
		Waitable<Pipe<String>> waitable;
		String xmlString;
		while(true){
			waitable = waiter.waitNext();
			xmlString = waitable.getParentComponent().dequeue();
			if(xmlString != null){
				if(compile(xmlString) == false){
					//TODO: send error
					throw new CompilerException();
				}
			}
			else{
				//TODO: send error
				break;
			}
		}
	}

	@Override
	public void respawn() {
		// TODO Auto-generated method stub

	}

	private boolean compile(String xml){
		StringReader reader = new StringReader(xml);
		ClassTreeManager ctm = new ClassTreeManager();
		Compiler c = new Compiler();
		try {
			ctm.createJavaFiles(defaultPackage, reader, null);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		File dir = new File(ctm.getParameterManager().getFileDir() + ctm.getParameterManager().getPerlaDevice().getName());
		return c.compileFiles(dir, null);
	}
	
}
